﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Xml;
using System.IO;
using System.Data.SqlClient;

namespace Tayninh2011
{
    class TnUtilities : ITnUtilComponent, ITnUtilitiesFile, ITnUtilities //:ITnUtilitiesFile,ITnUtilComponent,ITnUtilities
    {
        SqlConnection sqlConn=null;
        public TnUtilities()
        {

        }
        public TnUtilities(SqlConnection sqlConnection)
        {
            sqlConn = sqlConnection;
        }
        public string GetNameFromPathIncludeDot(string path, char[] split)
        {
            //string strName = "";
            string[] arrPath = null;
            char[] charSplit=split;
            arrPath = path.Split(charSplit);
            //for (int i = 0; i < arrPath.Length; i++)
            //{

            //}
           
            return arrPath[arrPath.Length-1];
        }
        public string GetPathWithoutName(string path, char[] split)
        {
            string[] arrPath = null;
            string strName = "";
            char[] charSplit = split;
            arrPath = path.Split(charSplit);
            strName = arrPath[arrPath.Length - 1];
            //MessageBox.Show(path.Substring(0, path.Length - strName.Length));
            return path.Substring(0, path.Length - strName.Length-1);
        }
        public void TnAddTabpageWithDatagridview(TabControl tabControl, string nameTab,string textTab,int widthPage,int heightPage,string nameGrid,int widthGrid,int heightGrid)
        {
            //System.Drawing.Size gridSize = new System.Drawing.Size();
            TnTabPage newTabpage = new TnTabPage(nameTab);
            DataGridView newDatagrid = new DataGridView();

            newTabpage.IsSelected = false;
            newTabpage.Controls.Add(newDatagrid);
            newTabpage.Location = new System.Drawing.Point(4, 22);
            newTabpage.Name = nameTab;
            newTabpage.Text = textTab;
            newTabpage.Padding = new System.Windows.Forms.Padding(3);
            newTabpage.Size = new System.Drawing.Size(widthPage, heightPage);
            //newTabpage.TabIndex = 0;
            //newTabpage.Text = "tabPage1";
            newTabpage.UseVisualStyleBackColor = true;
            

            newDatagrid.AllowUserToAddRows = false;
            newDatagrid.AllowUserToDeleteRows = false;
            DataGridViewCellStyle dataGridViewCellStyle2 = new DataGridViewCellStyle();
            DataGridViewCellStyle dataGridViewCellStyle7 = new DataGridViewCellStyle();
            DataGridViewCellStyle dataGridViewCellStyle8 = new DataGridViewCellStyle();
            DataGridViewCellStyle dataGridViewCellStyle9 = new DataGridViewCellStyle();
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control;
            dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            newDatagrid.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;

            dataGridViewCellStyle7.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle7.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            dataGridViewCellStyle7.ForeColor = System.Drawing.Color.Black;
            dataGridViewCellStyle7.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            newDatagrid.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle7;
            newDatagrid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
            newDatagrid.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedHeaders;
            newDatagrid.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
            newDatagrid.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            newDatagrid.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Raised;
            newDatagrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            newDatagrid.Dock = System.Windows.Forms.DockStyle.Fill;
            newDatagrid.Location = new System.Drawing.Point(3, 3);
            newDatagrid.Name = nameGrid;
            newDatagrid.ReadOnly = false;
            dataGridViewCellStyle8.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle8.BackColor = System.Drawing.SystemColors.Control;
            dataGridViewCellStyle8.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle8.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle8.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle8.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle8.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            newDatagrid.RowHeadersDefaultCellStyle = dataGridViewCellStyle8;
            dataGridViewCellStyle9.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            newDatagrid.RowsDefaultCellStyle = dataGridViewCellStyle9;
            newDatagrid.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            newDatagrid.ShowEditingIcon = true;
            newDatagrid.Size = new System.Drawing.Size(widthGrid, heightGrid);
            //newDatagrid.TabIndex = 1;
            newDatagrid.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(datagrid_CellClick);
            tabControl.Controls.Add(newTabpage);
            //tabControl.SelectedIndexChanged += new System.EventHandler(tab_Click);
        }

        public TabControl TnCreateTabControl(string name,int x,int y, int widthTab,int heightTab,int tabIndex)
        {
            TabControl newTabControl = new TabControl();
            TnTabPage newPage = new TnTabPage("page1");
            newTabControl.Controls.Add(newPage);
            newTabControl.Location = new System.Drawing.Point(x, y);
            newTabControl.Name = name;
            newTabControl.SelectedIndex = 0;
            newTabControl.Size = new System.Drawing.Size(widthTab, heightTab);
            newTabControl.TabIndex = tabIndex;
            
            return newTabControl;
        }
        private void datagrid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView datag = (DataGridView)sender;
            //MessageBox.Show(datag.Rows[e.RowIndex].Cells[0].Value.ToString());
        }
        public static void StartService(string service_name, int timeoutMilliseconds)
        {
            
            ServiceController service = new ServiceController(service_name);
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
                //throw new InvalidCastException();
                //return true;
            }
            catch
            {
                //MessageBox.Show("Thử Đăng nhập lại lần nữa hoặc start service 'esri-sde' bằng tay");
                //return false;
            }
        }


        #region ITnUtilitiesFile Members

        void ITnUtilitiesFile.CreateXmlFile(string AuthorName, string[,] obj_with_val, string name, string path)
        {
            string nameXml =path+ name + ".xml";
            XmlTextWriter writer = new XmlTextWriter(nameXml, System.Text.Encoding.UTF8);
            writer.WriteStartDocument(true);
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 2;
            writer.WriteStartElement(AuthorName);
            for (int i = 0; i < obj_with_val.Length / 2; i++)
            {
                createNode(obj_with_val[i, 0], obj_with_val[i, 1], writer);
            }
            //createNode(value[i], writer);
            //createNode("2", "Product 2", "2000", writer);
            //createNode("3", "Product 3", "3000", writer);
            //createNode("4", "Product 4", "4000", writer);
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();
        }
        

        #endregion


        private void createNode(string obj,string value, XmlTextWriter writer)
        {
            writer.WriteStartElement(obj);
            writer.WriteString(value);
            writer.WriteEndElement();
            //writer.WriteStartElement("Product_id");
            //writer.WriteString(pID);
            //writer.WriteEndElement();
            //writer.WriteStartElement("Product_name");
            //writer.WriteString(pName);
            //writer.WriteEndElement();
            //writer.WriteStartElement("Product_price");
            //writer.WriteString(pPrice);
            //writer.WriteEndElement();
            //writer.WriteEndElement();
        }

        #region ITnUtilitiesFile Members


        string[,] ITnUtilitiesFile.ReadUserInfoFromXmlFile(string name, string path)
        {
            string[,] objWithVal = new string[,] { { "", "" } };
            try
            {
                XmlDataDocument xmldoc = new XmlDataDocument();
                XmlNodeList xmlnode;
                string nameXml = "";
                if (path != " ")
                {
                    nameXml = path + name + ".xml";
                }
                else
                {
                    nameXml = name + ".xml";
                }
                

                FileStream fs = new FileStream(nameXml, FileMode.Open, FileAccess.Read);
                xmldoc.Load(fs);
                xmlnode = xmldoc.GetElementsByTagName("server");
                string server = xmlnode.Item(0).InnerText;
                xmlnode = xmldoc.GetElementsByTagName("database");
                string database = xmlnode.Item(0).InnerText;
                xmlnode = xmldoc.GetElementsByTagName("uid");
                string user = xmlnode.Item(0).InnerText;
                xmlnode = xmldoc.GetElementsByTagName("pwd");
                string pass = xmlnode.Item(0).InnerText;
                objWithVal = new string[,] { { "server", server }, { "database", database }, { "uid", user }, { "pwd", pass } };
                fs.Close();
            }
            catch (Exception e) { MessageBox.Show(e.Message); }

            return objWithVal;
        }

        List<List<string>> ITnUtilitiesFile.ReadLayersFormXmlFile(String name, String path)
        {
            List<List<string>> objWithVal = new List<List<String>>();
            List<String> lstThua = new List<string>();
            List<String> lstDuong = new List<string>();
            List<String> lstHem = new List<string>();
            List<String> lstGiadat = new List<string>();
            try
            {
                XmlDataDocument xmldoc = new XmlDataDocument();
                XmlNodeList xmlnode;
                string nameXml = "";
                if (path != " ")
                {
                    nameXml = path + name + ".xml";
                }
                else
                {
                    nameXml = name + ".xml";
                }


                FileStream fs = new FileStream(nameXml, FileMode.Open, FileAccess.Read);
                xmldoc.Load(fs);
                xmlnode = xmldoc.GetElementsByTagName("thua");
                foreach(XmlNode node in xmlnode)
                {
                    lstThua.Add(node.InnerText);
                }
                
                xmlnode = xmldoc.GetElementsByTagName("duong");
                foreach (XmlNode node in xmlnode)
                {
                    lstDuong.Add(node.InnerText);
                }
                
                xmlnode = xmldoc.GetElementsByTagName("hem");
                foreach (XmlNode node in xmlnode)
                {
                    lstHem.Add(node.InnerText);
                }

                xmlnode = xmldoc.GetElementsByTagName("thua_giadat");
                foreach (XmlNode node in xmlnode)
                {
                    lstGiadat.Add(node.InnerText);
                }
                objWithVal.Add(lstThua);
                objWithVal.Add(lstDuong);
                objWithVal.Add(lstHem);
                objWithVal.Add(lstGiadat);
                fs.Close();
            }
            catch { }
            return objWithVal;
        }

        void ITnUtilitiesFile.CreateXmlFile(string AuthorName, List<String[]> obj_with_val, string name, string path)
        {
            //luu y obj_with_val la list cac mang 2 gia tri
            string nameXml = path + name + ".xml";
            XmlTextWriter writer = new XmlTextWriter(nameXml, System.Text.Encoding.UTF8);
            writer.WriteStartDocument(true);
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 2;
            writer.WriteStartElement(AuthorName);
            for (int i = 0; i < obj_with_val.Count; i++)
            {
                createNode(obj_with_val[i][0], obj_with_val[i][1], writer);
            }
            //createNode(value[i], writer);
            //createNode("2", "Product 2", "2000", writer);
            //createNode("3", "Product 3", "3000", writer);
            //createNode("4", "Product 4", "4000", writer);
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();
        }

        #endregion

        #region ITnUtilComponent Members

        ComboBox ITnUtilComponent.CbxLayers(string[,] info)
        {
            ComboBox myCbx = new ComboBox();
            ITnQueryFilter queryFilter = new TnQueryFilterBuilder()
                .SqlConnection(info)
                .Table("sde.SDE_layers")
                .Fields("table_name")
                .BuildQuery();
            queryFilter.Excute();
            SqlDataReader reader = queryFilter.GetResultCursor();
            while (reader.Read())
            {
                myCbx.Items.Add(reader.GetValue(0).ToString());
            }
            
            return myCbx;
        }
        ComboBox ITnUtilComponent.CbxLayers(string[,] info, String text, Boolean isHead)
        {
            ComboBox myCbx = new ComboBox();
            ITnQueryFilter queryFilter = new TnQueryFilterBuilder()
                .SqlConnection(info)
                .Table("sde.SDE_layers")
                .Fields("table_name")
                .BuildQuery();
            queryFilter.Excute();
            SqlDataReader reader = queryFilter.GetResultCursor();
            while (reader.Read())
            {
                myCbx.Items.Add(reader.GetValue(0).ToString());
            }
            myCbx.Text = text;
            if (isHead)
            {
                myCbx.ForeColor = System.Drawing.Color.Red;
            }
            return myCbx;
        }

        ComboBox ITnUtilComponent.CbxLayers(string[,] info, String text)
        {
            ComboBox myCbx = new ComboBox();
            ITnQueryFilter queryFilter = new TnQueryFilterBuilder()
                .SqlConnection(info)
                .Table("sde.SDE_layers")
                .Fields("table_name")
                .BuildQuery();
            queryFilter.Excute();
            SqlDataReader reader = queryFilter.GetResultCursor();
            while (reader.Read())
            {
                myCbx.Items.Add(reader.GetValue(0).ToString());
            }
            myCbx.Text = text;
            return myCbx;
        }

        #endregion

        public static string getNameOnly(string fullNameWithDot)
        {
            string[] arrName = fullNameWithDot.Split('.');
            int len = arrName.Length;
            return arrName[len - 1];
        }

        #region ITnUtilities

        List<string[]> ITnUtilities.GetLstOfLayers(List<List<string>> list)
        {
            List<string[]> result = new List<string[]>();
            int len = list[0].Count;
            for (int i = 0; i < len; i++)
            {
                result.Add(new string[] { "thua", list[0][i] });
            }

            len = list[1].Count;
            for (int i = 0; i < len; i++)
            {
                result.Add(new string[] { "duong", list[1][i] });
            }

            len = list[2].Count;
            for (int i = 0; i < len; i++)
            {
                result.Add(new string[] { "hem", list[2][i] });
            }

            len = list[3].Count;
            for (int i = 0; i < len; i++)
            {
                result.Add(new string[] { "thua_giadat", list[3][i] });
            }

            return result;
        }

        #endregion ITnUtilities

        public static string ArrayToString(object[] array)
        {
            string result = String.Empty;
            foreach (object o in array)
            {
                result = o.ToString() + ",";
            }
            result.TrimEnd(',');
            return result;
        }

        public static string ConverUserinfoToConnStr(string[,] userInfo)
        {
            string result = String.Empty;


            return result;
        }
    }

}
